/*
 *      Fischer Chess Club
 *      Copyright (c) 2010 Ryan Chiu
 *      All rights reserved.
 *      
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 3 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fischer;

import java.io.DataInputStream;
import java.io.File;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Authenticate {

	private static Scanner s;

	@SuppressWarnings("deprecation")
	public static void authenticate(String username, DataInputStream inp,
			PrintStream outp, Socket socket) {
		try {
			if (userExists(username)) {
				outp.println("\""
						+ username
						+ "\" is a registered handle. If this is your handle, please type the password now.");
				outp.println("password: ");
				String password = inp.readLine().toString();
				System.out.println(socket.isConnected()); // it is good to add
															// verifications
															// like this
				// helps make debugging easier.
				if (checkPassword(username, password)) {
					outp.println();
					outp.print(Fischer.prompt);
				} else {
					outp.println("Wrong password. Try again.");
					socket.close();
				}
			} else if (!userExists(username)) {
				outp.println("\"" + username + "\" is NOT a registered handle.");
				socket.close();
			} else {
				System.out.println("Failed to authenticate user.");
			}
		} catch (Exception e) {
			System.err.println("Authentication error: ");
			e.printStackTrace(System.err);
		}
	}

	public static boolean checkPassword(String username, String password)
			throws Exception {
		try {
			s = new Scanner(new File(Config.USER_DIR + "\\" + username));
		} catch (Exception e) {
			System.err.println("Password check error: "+e);
			e.printStackTrace(System.err);
			return false;
		}
		
		String dline = s.nextLine();
		String pass = dline.replaceAll("Password: ", "");
		//int spaceIndex = line.indexOf(" ");
		//String pass = line.substring(0, spaceIndex);

		return password.equals(pass);
	}

	public static boolean userExists(String username) {
		String[] users = Config.USER_DIR.list();
		System.out.println(users == null);
		for (int i = 0; i < users.length; i++) {
			if (users[i].equalsIgnoreCase(username)) {
				return true;
			}
		}
		return false;
	}
}
